/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers;

import concursos.metadados.Tabela;
import controllers.exceptions.NonexistentEntityException;
import controllers.exceptions.PreexistingEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import concursos.metadados.Item;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author lucena
 */
public class TabelaJpaController {

    public TabelaJpaController() {
        emf = Persistence.createEntityManagerFactory("concursosPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Tabela tabela) throws PreexistingEntityException, Exception {
        if (tabela.getItens() == null) {
            tabela.setItens(new HashSet<Item>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Set<Item> attachedItens = new HashSet<Item>();
            for (Item itensItemToAttach : tabela.getItens()) {
                itensItemToAttach = em.getReference(itensItemToAttach.getClass(), itensItemToAttach.getId());
                attachedItens.add(itensItemToAttach);
            }
            tabela.setItens(attachedItens);
            em.persist(tabela);
            for (Item itensItem : tabela.getItens()) {
                Tabela oldTabelaOfItensItem = itensItem.getTabela();
                itensItem.setTabela(tabela);
                itensItem = em.merge(itensItem);
                if (oldTabelaOfItensItem != null) {
                    oldTabelaOfItensItem.getItens().remove(itensItem);
                    oldTabelaOfItensItem = em.merge(oldTabelaOfItensItem);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findTabela(tabela.getId()) != null) {
                throw new PreexistingEntityException("Tabela " + tabela + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Tabela tabela) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Tabela persistentTabela = em.find(Tabela.class, tabela.getId());
            Set<Item> itensOld = persistentTabela.getItens();
            Set<Item> itensNew = tabela.getItens();
            Set<Item> attachedItensNew = new HashSet<Item>();
            for (Item itensNewItemToAttach : itensNew) {
                itensNewItemToAttach = em.getReference(itensNewItemToAttach.getClass(), itensNewItemToAttach.getId());
                attachedItensNew.add(itensNewItemToAttach);
            }
            itensNew = attachedItensNew;
            tabela.setItens(itensNew);
            tabela = em.merge(tabela);
            for (Item itensOldItem : itensOld) {
                if (!itensNew.contains(itensOldItem)) {
                    itensOldItem.setTabela(null);
                    itensOldItem = em.merge(itensOldItem);
                }
            }
            for (Item itensNewItem : itensNew) {
                if (!itensOld.contains(itensNewItem)) {
                    Tabela oldTabelaOfItensNewItem = itensNewItem.getTabela();
                    itensNewItem.setTabela(tabela);
                    itensNewItem = em.merge(itensNewItem);
                    if (oldTabelaOfItensNewItem != null && !oldTabelaOfItensNewItem.equals(tabela)) {
                        oldTabelaOfItensNewItem.getItens().remove(itensNewItem);
                        oldTabelaOfItensNewItem = em.merge(oldTabelaOfItensNewItem);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                long id = tabela.getId();
                if (findTabela(id) == null) {
                    throw new NonexistentEntityException("The tabela with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Tabela tabela;
            try {
                tabela = em.getReference(Tabela.class, id);
                tabela.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The tabela with id " + id + " no longer exists.", enfe);
            }
            Set<Item> itens = tabela.getItens();
            for (Item itensItem : itens) {
                itensItem.setTabela(null);
                itensItem = em.merge(itensItem);
            }
            em.remove(tabela);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Tabela> findTabelaEntities() {
        return findTabelaEntities(true, -1, -1);
    }

    public List<Tabela> findTabelaEntities(int maxResults, int firstResult) {
        return findTabelaEntities(false, maxResults, firstResult);
    }

    private List<Tabela> findTabelaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Tabela as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Tabela findTabela(long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Tabela.class, id);
        } finally {
            em.close();
        }
    }

    public int getTabelaCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Tabela as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
